package com.shaw.study.springx.transaction;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by asus on 2018/5/15.
 */
public class TransactionManager {
    private static DataSource dataSource;
    private final static TransactionManager transactionManager = new TransactionManager();
    private TransactionManager(){
        Properties p = new Properties();
        p.put("driverClassName","com.mysql.jdbc.Driver");
        p.put("url", "jdbc:mysql://localhost:3306/test?useUnicode=true&autoReconnect=true&rewriteBatchedStatements=TRUE");
        p.put("username", "root");
        p.put("password", "root");
        p.put("initialSize", "1");
        p.put("minIdle", "1");
        p.put("maxActive", "20");
        p.put("maxWait", "60000");
        p.put("timeBetweenEvictionRunsMillis", "60000");
        p.put("minEvictableIdleTimeMillis", "300000");
        p.put("validationQuery", "SELECT 'x' from dual");
        p.put("testWhileIdle", "true");
        p.put("testOnBorrow", "false");
        p.put("testOnReturn", "false");
        p.put("poolPreparedStatements", "true");
        p.put("maxPoolPreparedStatementPerConnectionSize", "20");
        p.put("filters", "stat");
        try {
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static TransactionManager getInstances(){
        return transactionManager;
    }

    public Connection getConnection() throws SQLException {
        return ThreadConnectionHolder.getConnection(dataSource);
    }

    public void start() throws SQLException {
        Connection connection = getConnection();
        connection.setAutoCommit(false);
    }

    public void rollback(){
        Connection connection = null;
        try{
            connection  = getConnection();
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void commit() throws SQLException {
        Connection connection = getConnection();
        connection.commit();
    }

    public void close() throws SQLException {

        Connection connection = getConnection();
        connection.setAutoCommit(true);
        connection.close();
    }
}
